package com.zzh.myapplication.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.icarplus.car.R;
import net.icarplus.car.app.MyApplication;
import net.icarplus.car.bean.CarInfo;
import net.icarplus.car.bean.RentalListBean;
import net.icarplus.car.bean.RentalResultInfo;
import net.icarplus.car.bean.ResultInfo;
import net.icarplus.car.constant.UrlValues;
import net.icarplus.car.manager.BaseActivity;
import net.icarplus.car.manager.MainSelect;
import net.icarplus.car.service.PublicRequest;
import net.icarplus.car.tools.LoadingUtil;
import net.icarplus.car.tools.T;
import net.icarplus.car.tools.ToolBarHelper;
import net.icarplus.car.views.MultiDirectionSlidingDrawer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名称：icarplus-car-android
 * 类描述：
 * 创建人：Gophy
 * 创建时间：16/3/9 10:56
 * 修改人：Gophy
 * 修改时间：16/3/9 10:56
 * 修改备注：
 */
public class NearbyActivity extends BaseActivity implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, AMap.OnMapClickListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener, AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener {

    private MapView mapView;
    private AMap aMap;
    private Toolbar toolbar;

    public AMapLocationClient mLocationClient = null;

    public AMapLocationClientOption mLocationOption = null;
    private UiSettings mUiSettings;

    public LinearLayout llMainNearby;

    private Marker currentMarker;

    private LoadingUtil loadingUtil;

    private ImageView ivCarShowType;

    private ArrayList<MarkerOptions> markerOptionsList = new ArrayList<MarkerOptions>();


    private MarkerOptions markerOption;
    private Button btnCurLoc;

    private double getLat = 0.0;
    private double getLon = 0.0;


    private ImageView iv_car_left;
    private ImageView iv_car_right;

    private MultiDirectionSlidingDrawer mDrawer;
    private JSONArray array;

    private int temp = 0;

    private View nearbyContent;

    private TextView tvCarName;
    private TextView tvToalCar;

    private RadioGroup mRadioGroup;

    private String rentCarNum;

    private List<RentalListBean> rentalList = new ArrayList<RentalListBean>();

    private ResultInfo resultNearbyCars;
    private List<CarInfo> nearbyCars = new ArrayList<CarInfo>();

    private String pointName;



    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 10000:
                    NearbyActivity.this.loadingUtil.stopShowLoading();

                    refreshCars(msg.obj.toString());

                    break;

                case 2000:
                    NearbyActivity.this.loadingUtil.stopShowLoading();
                    refreshBottomCarsInfo(msg.obj.toString());
                    break;
                case 30000:
                    NearbyActivity.this.loadingUtil.stopShowLoading();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mapView = (MapView) findViewById(R.id.amaps);
        mapView.onCreate(savedInstanceState);
    }

    @Override
    public void setContent() {
        setContentView(R.layout.activity_nearby);
    }

    @Override
    public void initComponent() {


        mapView = (MapView) findViewById(R.id.amaps);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        ivCarShowType = (ImageView) findViewById(R.id.iv_show_car_type);
        btnCurLoc = (Button) findViewById(R.id.current_location_btn);
        MainActivity.mainPage = MainSelect.NEARBY;

        iv_car_left = (ImageView) findViewById(R.id.iv_car_left);
        iv_car_right = (ImageView) findViewById(R.id.iv_car_right);
        mDrawer = (MultiDirectionSlidingDrawer) findViewById(R.id.drawer);

        nearbyContent = findViewById(R.id.content);
        tvCarName = (TextView) nearbyContent.findViewById(R.id.tv_car_name);
        tvToalCar = (TextView) nearbyContent.findViewById(R.id.tv_total_car_num);
        mRadioGroup = (RadioGroup) nearbyContent.findViewById(R.id.tab_select);
        llMainNearby = (LinearLayout) findViewById(R.id.ll_order);

    }

    @Override
    public void setListener() {
        ivCarShowType.setOnClickListener(this);
        btnCurLoc.setOnClickListener(this);
        ToolBarHelper.setNormalTitleAndBack(this, toolbar, getString(R.string.bottom_nearby));


        if (aMap == null) {
            aMap = mapView.getMap();
            mUiSettings = aMap.getUiSettings();
        }

        aMap.setOnMarkerClickListener(this);
        aMap.setOnMapClickListener(this);
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式


        iv_car_left.setOnClickListener(this);
        iv_car_right.setOnClickListener(this);

        mRadioGroup.setOnCheckedChangeListener(this);
        llMainNearby.setOnClickListener(this);
    }

    @Override
    public void onAfterInit() {

        setlocInfo();


    }

    private void setlocInfo() {
        if (MyApplication.aAMapLocation == null) {
            initMap();
        } else {
            setupIconAndLoc(MyApplication.aAMapLocation);
        }
    }

    private void getRentalRequest(AMapLocation mAMapLocation) {
        JSONObject jsonObject = new JSONObject();
//        String testUrl = "http://d.icarplus.net/app_version/test_loc.json";

        try {
            jsonObject.put("positionLon", mAMapLocation.getLongitude() + "");
            jsonObject.put("positionLat", mAMapLocation.getLatitude() + "");
            this.loadingUtil = new LoadingUtil(this, getString(R.string.loading_text));
            this.loadingUtil.startShowLoading();
            PublicRequest.doGetRequest(UrlValues.GET_RENTAL_URL, handler, jsonObject, 10000, 30000);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void initMap() {
        this.loadingUtil = new LoadingUtil(this, "定位中...");
        this.loadingUtil.startShowLoading();
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setMockEnable(false);
        aMap.setMyLocationRotateAngle(180);
        aMap.setLocationSource(this);// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
        mUiSettings.setScaleControlsEnabled(true);// 设置地图默认的比例尺是否显示
        mUiSettings.setZoomControlsEnabled(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {

            MyApplication.aAMapLocation = amapLocation;

            setupIconAndLoc(amapLocation);
        }

    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (currentMarker != null) {
            currentMarker.hideInfoWindow();
        }

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        mDrawer.open();

        currentMarker = marker;

        currentMarker.showInfoWindow();

        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_show_car_type:
                break;
            case R.id.current_location_btn:
                moveToCurrentLoc(getLat, getLon);
                break;
            case R.id.iv_car_left:
                iv_car_right.setVisibility(View.VISIBLE);
                if (temp >= 0) {
                    temp--;
                }
                if (temp == 0) {
                    iv_car_left.setVisibility(View.GONE);
                }
                changeRentCarPointPos(temp);
                break;

            case R.id.iv_car_right:
                iv_car_left.setVisibility(View.VISIBLE);
                if (temp < rentalList.size()) {
                    temp++;
                }
                if (temp == rentalList.size() - 1) {
                    iv_car_right.setVisibility(View.GONE);
                }
                changeRentCarPointPos(temp);
                break;

            default:
                break;
        }

    }
    private void moveToCurrentLoc(double lat, double lon) {
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(
                lat, lon)));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
    }
    private void setupIconAndLoc(AMapLocation amapLocation) {
        getLat = amapLocation.getLatitude();
        getLon = amapLocation.getLongitude();
        moveToCurrentLoc(getLat, getLon);
        markerOption = new MarkerOptions();
        markerOption.icon(BitmapDescriptorFactory
                .fromResource(R.mipmap.zb2));
        //markerOption.icon(BitmapDescriptorFactory.fromBitmap(getMyBitmap("test")));
        markerOption.position(new LatLng(amapLocation.getLatitude(),
                amapLocation.getLongitude()));
        markerOption.draggable(true);
        aMap.addMarker(markerOption);
        getRentalRequest(amapLocation);
    }
    private void addMarkers(double lat, double lon) {
        markerOption = new MarkerOptions();
        for (int i = 0; i < 10; i++) {
            LatLng latLng = new LatLng(lat, lon);
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(getMyBitmap(rentCarNum)));
            markerOption.position(latLng);
            markerOption.draggable(true);
            markerOption.title(rentCarNum + "辆");
            aMap.addMarker(markerOption);
            currentMarker = aMap.addMarker(markerOption);
            //currentMarker.showInfoWindow();

        }
    }

    protected Bitmap getMyBitmap(String pm_val) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.icon_1_1334).copy(Bitmap.Config.ARGB_8888, true);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight());
        Canvas canvas = new Canvas(bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setFakeBoldText(true);
        textPaint.setTextSize(22f);
        textPaint.setColor(getResources().getColor(R.color.green));
        canvas.drawText(pm_val, 27, 40, textPaint);// 设置bitmap上面的文字位置
        return bitmap;
    }

    private void refreshCars(String resultList) {
        if (resultList != null) {

            Gson gson = new Gson();
            RentalResultInfo result = gson.fromJson(resultList,
                    new TypeToken<RentalResultInfo>() {
                    }.getType());
            RentalResultInfo mRentalResultInfo = result;
            rentalList = result.queryList;
            RentalListBean mRentalListBean = null;
            for (int i = 0; i < rentalList.size(); i++) {
                mRentalListBean = rentalList.get(i);
                double rtLat = Double.parseDouble(mRentalListBean.rtLat);
                double rtLon = Double.parseDouble(mRentalListBean.rtLon);
                rentCarNum = mRentalListBean.rtCarNum;
                addMarkers(rtLat, rtLon);
                changeRentCarPointPos(temp);
                currentMarker.showInfoWindow();
                mDrawer.open();
                iv_car_left.setVisibility(View.GONE);
            }


        }
    }

    private void changeRentCarPointPos(int index) {
        index = temp;
        RentalListBean mRentalListBean = null;

        mRentalListBean = rentalList.get(index);
        double rtLat = Double.parseDouble(mRentalListBean.rtLat);
        double rtLon = Double.parseDouble(mRentalListBean.rtLon);


        pointName = mRentalListBean.rtName;

        tvCarName.setText(mRentalListBean.rtName);
        tvToalCar.setText(mRentalListBean.rtCarNum);


        JSONObject json = new JSONObject();
        try {
            json.put("rtNo", mRentalListBean.rtNo);
//            loadingUtil = new LoadingUtil(this, getString(R.string.loading_text));
//            this.loadingUtil.startShowLoading();
            PublicRequest.doGetRequest(UrlValues.GET_RENTAL_CAR_INFO_URL, handler, json, 2000, 30000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        moveToCurrentLoc(rtLat, rtLon);


    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
        Intent intent = new Intent();
        switch (checkId) {
            case R.id.rb_rent_now:
                intent.setClass(NearbyActivity.this, DivideTimeCarActivity.class);
                start_Activity(intent);
                break;
            case R.id.rb_tell_me_way:
                T.showShort("导航中...");
                break;
            default:
                break;
        }

    }

    private void refreshBottomCarsInfo(String carsInfo) {
        if (carsInfo != null) {
            Gson gson = new Gson();
            ResultInfo result = gson.fromJson(carsInfo,
                    new TypeToken<ResultInfo>() {
                    }.getType());

            nearbyCars = result.queryList;

            CarInfo nearbyCarInfo = null;
            for (int i = 0; i < nearbyCars.size(); i++) {
                nearbyCarInfo = nearbyCars.get(i);

//                System.out.println("fadfs::" + nearbyCarInfo.addr);
            }

        }
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.map_popup_window, null);
        render(marker, infoWindow);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        View infoContent = getLayoutInflater().inflate(
                R.layout.map_popup_window, null);
        render(marker, infoContent);
        return infoContent;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
    }


    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = (TextView) view.findViewById(R.id.tv_car_num);
        TextView pointUI = (TextView) view.findViewById(R.id.tv_point_name);
        titleUi.setText(title);
        pointUI.setText(pointName);
    }

}
